<template>
  <el-dialog v-model="visible" :title="title">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="6em">
      <el-form-item label="名称" prop="key">
        <el-input v-model="form.key" placeholder="输入关键字" />
      </el-form-item>
      <el-form-item label="值" prop="value">
        <el-input v-model="form.value" placeholder="输入值" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" placeholder="输入描述" />
      </el-form-item>
      <el-form-item label="是否有效" prop="is_active" required>
        <el-switch v-model="form.is_active" />
      </el-form-item>
      <el-form-item label="是否公开配置" prop="is_public" required>
        <el-switch v-model="form.is_public" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="fieldStore.loading.create || fieldStore.loading.update"
          @click="handleConfirm"
        >
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { defineModel } from "vue";
import { useFieldStoreHook } from "@/store/modules/system/field";
import { FieldType } from "@/api/system/field";

const fieldStore = useFieldStoreHook();

export type FormType = "add" | "edit";

export interface Props {
  type: FormType;
  form?: FieldType;
}

const visible = defineModel({ type: Boolean, default: false });

const emits = defineEmits(["confirm"]);

const props = defineProps<Props>();

const formRef = ref();

const form = reactive<Partial<FieldType>>({
  is_active: true,
  key: "",
  value: "",
  description: "",
  is_public: true,
});

const rules = {
  key: [
    {
      required: true,
      message: "请输入关键字",
      trigger: "change",
    },
  ],
  value: [
    {
      required: true,
      message: "请输入值",
      trigger: "change",
    },
  ],
};

const title = computed(() => {
  return props.type === "add" ? "新增" : "编辑";
});

watch(visible, (val) => {
  if (val) {
    if (props.type === "edit") {
      Object.assign(form, props.form);
    }
  } else {
    form.key = "";
    form.value = "";
    form.description = "";
    form.is_active = true;
    form.is_public = true;
  }
});

function handleConfirm() {
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (props.type === "add") {
        await fieldStore.fetchCreateField(form);
      } else {
        await fieldStore.fetchUpdateField(form);
      }
      visible.value = false;
      emits("confirm");
    }
  });
}
</script>

<style scoped lang="scss"></style>
